package org.zjx.analysis.tap;

import lombok.Getter;
import org.zjx.analysis.BaseAnalysis;
import org.zjx.core.IWindow;
import org.zjx.enums.FontType;
import org.zjx.identify.PaneUtil;
import org.zjx.util.ImageUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Getter
public abstract class BaseTabAnalysis extends BaseAnalysis {
    protected Point location;

    public BaseTabAnalysis(IWindow window, BufferedImage screenshot) {
        super(window, screenshot);
    }

    @Override
    protected void analysis() {
        this.location = location();
    }

    private Point location() {
        Rectangle locationRect = conversion(windowArea,new Rectangle(getContentArea().x - 50, getContentArea().y -30,getContentArea().width + 100,getContentArea().height + 30));
        PaneUtil paneUtil = new PaneUtil(ImageUtil.cutImage(screenshot,locationRect), 5, Collections.singletonList(new Color(248, 252, 248)));
        List<Rectangle> rects = paneUtil.detectRect();
        if (rects.isEmpty()) return null;
        String location = wordToStr(identifyFont(conversionReverse(windowArea,conversion(locationRect,rects.get(0))), Collections.singletonList(new Color(255, 255, 0)), FontType.LOCATION, 0,false));
        return matcherMap(location);
    }


    public abstract Rectangle getContentArea();


    private Point matcherMap(String location) {
        String regex = "([0-9]+)，([0-9]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(location);
        if (matcher.find()) {
            int x = Integer.parseInt(matcher.group(1));
            int y = Integer.parseInt(matcher.group(2));
            return new Point(x, y);
        } else {
            return null;
        }
    }
}
